import gulp from 'gulp';
import gulpLoadPlugins from 'gulp-load-plugins';
import del from 'del';

const $ = gulpLoadPlugins();

import webpack from 'webpack';
import webpackConfig from './webpack.production.config';

const config = {
    src: 'app/',
    dist: 'dist/',
    cssSrc: [
        'app/{styles,css}/{,*/}*.scss',
        '!app/{styles,css}/_*/*'
    ]
}

gulp.task('html', () => {
    const assets = $.useref.assets({
        searchPath: ['.tmp', '.tmp/scripts', '.tmp/styles'],
        transformPath(filePath){
            return filePath
        }
    });

    return gulp.src(['app/views/{detail,list,mylist,clear}.html'])
        .pipe(assets)
        .pipe($.rev())
        .pipe(gulp.dest('dist'))
        .pipe(assets.restore())
        .pipe($.useref())
        .pipe($.revReplace({
            prefix:'http://static.tuan.ymatou.com'
        }))
        .pipe($.filter('*.html'))
        .pipe(gulp.dest('views'));
});

gulp.task('webpack',(callback)=>{
    webpack(
      webpackConfig
    , function(err, status) {
      if(err){
        console.err('webpack ERR: '+err)
      }
      gulp.start('copy:html');
      callback && callback()
    });
});

gulp.task('copy:html',()=>{
   return gulp.src('dist/views/*.html')
    .pipe(gulp.dest('views'));
});

gulp.task('clean:pre', del.bind(null, ['.tmp','views', 'dist']));

//rm node-sass 会出错 删除unlink失效，暂时不删除 后续让发布remove
gulp.task('clean:post', del.bind(null, ['1dist/app','node_modules/*','!node_modules/express','!node_modules/ymt-node-watch','!node_modules/node-sass']));

gulp.task('build:test', ['clean:pre', 'webpack'],()=>{
    gulp.start('html');
});

gulp.task('build', ['build:test'],()=>{
    gulp.start('clean:post');
});